<template>
  <div>
    <el-form ref="deptForm" label-width="120px" :model="form" :rules="deptRules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="managerId">
        <el-select v-model="form.managerId" style="width:80%" placeholder="请选择">
          <el-option v-for="item in employees" :key="item.id" :value="item.id" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getSimpleEmpList } from '@/api/employees.js'
import { editDepartDetailById, getDepartDetailById, newAddDepartment } from '@/api/departments.js'
export default {
  name: 'DeptDialog',
  props: {
    // 把id和pid传过来，统称为id
    id: {
      type: [String, Number],
      required: true
    },
    // 把dialog是添加还是编辑的转态传过来
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }

  },
  data() {
    // code的自定义校验规则
    const validateCode = (rule, value, callback) => {
      let validCode = null
      if (this.isEdit) {
      // 如果dialog是编辑，则需要把当前code剔除数组，但是不能去修改原来的数组
        validCode = this.originList.filter(({ id }) => id !== this.id).some(({ code }) => code === value)
      } else {
        // 如果是添加,则在全部中去排除
        validCode = this.originList.some(({ code }) => code === value)
      }
      // console.log(validCode)

      validCode ? callback(new Error(`${value}已存在,请重新输入`)) : callback()
    }

    // name部门名称的自定义校验规则
    const validateName = (rule, value, callback) => {
      // 需求1：在一级部门下不能添加两个相同的部门
      // 需求2：编辑的时候，同级不重复
      let validCode = null
      if (this.isEdit) {
        // 根据当前的id，拿到pid，拿到pid相同的数据，且不能有自己
        const currentPid = this.originList.find(({ id }) => id === this.id).pid
        // 找pid相同的对象且不能有自己，且不能有父级部门
        validCode = this.originList.filter(({ pid, id }) => (pid === currentPid || id === currentPid) && this.id !== id).some(({ name }) => name === value)
      } else {
        validCode = this.originList.filter(({ pid }) => pid === this.id).some(({ name }) => name === value)
      }
      // console.log(validCode)

      validCode ? callback(new Error(`${value}已存在,请重新输入`)) : callback()
    }
    return {
      employees: [],
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        managerId: '', // 部门管理者
        introduce: ''// 部门介绍
      },

      // 表单的校验规则
      deptRules: {
        name: [
          { required: true, trigger: 'blur', message: '部门名称不能为空' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { trigger: ['blur', 'change'], validator: validateName }
        ],
        code: [
          { required: true, trigger: 'blur', message: '部门编码不能为空' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { trigger: ['blur', 'change'], validator: validateCode }
        ],
        managerId: [{ required: true, trigger: 'change', message: '部门负责人不能为空' }],
        introduce: [
          { required: true, trigger: 'blur', message: '部门介绍不能为空' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }

    }
  },

  created() {
    this.loadGetEmployee()
    this.loadGetDepartDetail()
  },
  methods: {
    // 根据ID查询部门详情，只有是编辑的时候才发请求
    async loadGetDepartDetail() {
      if (!this.isEdit) return
      const { data } = await getDepartDetailById(this.id)
      this.form = data
    },
    // 获取员工简单列表
    async loadGetEmployee() {
      try {
        const res = await getSimpleEmpList()
        this.employees = res.data
      } catch (error) {
        console.log(error)
      }
    },

    // 点击确定提交信息
    async hSubmit() {
      try {
      // 兜底校验
        await this.$refs.deptForm.validate()
        // 发请求前先判断是编辑还是添加
        let res = null
        if (!this.isEdit) {
          res = await newAddDepartment({ ...this.form, pid: this.id })
        } else {
          res = await editDepartDetailById(this.form)
        }
        // console.log(res)
        // 根据状态提示用户
        this.$message.success(res.message)
        // 再次发请求获取最新的数据，子传父，提醒父更新数据,并关闭dialog
        this.$emit('successChange')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    // 点击了取消
    hCancel() {
      // 点击了取消
      this.$emit('cancel')
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
